<template>
    <div id="movie-schedule">
      <!--搜索-->
      <div class="top">
        <el-col :span="12">
          <el-input placeholder="请输入内容" v-model="input" class="input-with-select" style="width: 100%">
            <el-button slot="append" icon="el-icon-search" @click="search">搜索</el-button>
          </el-input>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-button type="primary" size="small" @click="addSchedule">安排电影</el-button>
        </el-col>
      </div>
      <!--表格-->
      <div class="schedule-table">
        <el-table
          border
          :data="tableData"
          style="width: 100%">
          <el-table-column
            label="排片 ID"
            align="center"
            width="100"
            prop="scheduleId">
          </el-table-column>
          <el-table-column
            label="电影名"
            show-overflow-tooltip
            prop="filmName">
          </el-table-column>
          <el-table-column
            label="影院名"
            show-overflow-tooltip
            prop="cinemaName">
          </el-table-column>
          <el-table-column
            label="放映大厅"
            prop="hallName">
          </el-table-column>
          <el-table-column
            label="放映日期"
            prop="scheduleDate">
          </el-table-column>
          <el-table-column
            label="放映时间"
            prop="startTime">
          </el-table-column>
          <el-table-column
            label="结束时间"
            prop="endTime">
          </el-table-column>
          <el-table-column
            label="售价（元）"
            prop="price">
          </el-table-column>
          <el-table-column 
          width="100"
          align="center"
          label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="block" v-if="tableData.length">
        <el-pagination
          @current-change="currentChange"
          background
          layout="prev, pager, next"
          :page-size="8"
          :total="total">
        </el-pagination>
      </div>
      <!--添加排片-->
      <div>
        <el-dialog
          title="添加排片"
          :visible.sync="addDialogFormVisible"
          :modal-append-to-body="false"
          v-if="addDialogFormVisible"
          :show-close="false"
        >
          <el-form :label-position="labelPosition" :rules="rules" label-width="80px" :model="scheduleInfo">
            <el-form-item label="电影名" prop="movieValue">
              <el-col :span="12">
                <el-select v-model="scheduleInfo.movieValue" placeholder="请选择" @change="changeMovie" style="width: 100%">
                  <el-option
                    v-for="item in movieOptions"
                    :key="item.id"
                    :label="item.filmName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <!-- <el-form-item label="影院" prop="cinemaValue">
              <el-col :span="12">
                <el-input v-model="cinemaInfo.cinemaName" disabled="true"></el-input>
              </el-col>
            </el-form-item> -->
            <el-form-item label="影厅" prop="hallValue">
              <el-col :span="12">
                <el-select v-model="scheduleInfo.hallValue" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in hallOptions"
                    :key="item.id"
                    :label="item.hallName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
    
            <el-form-item label="放映日期" prop="movieShowDate">
              <el-col :span="12">
                <el-date-picker
                  v-model="scheduleInfo.movieShowDate"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="datePickerOptions"
                  value-format="yyyy-MM-dd"
                  @change="movieShowDateChange"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-col :span="12">
                <el-time-picker
                  v-model="scheduleInfo.startTime"
                  value-format="HH:mm:00"
                  placeholder="任意时间点"
                  style="width: 100%"
                   :picker-options="{
                    start: '09:00',
                    step: '00:05',
                    end: '00:00'
                  }"
                  @change="getEndTime(scheduleInfo.startTime,movieDuration)"
                  >
                </el-time-picker>
              </el-col>
            </el-form-item>
        
               <el-form-item label="结束时间" prop="endTime">
              <el-col :span="12">
                <el-time-picker
                  disabled
                  v-model="curEndTime"
                  value-format="HH:mm:00"
                  placeholder="结束时间"
                  style="width: 100%"
                  >
                </el-time-picker>
              </el-col>
            </el-form-item>
 
            <el-form-item label="售价" prop="ticketPrice">
              <el-col :span="12">
                <el-input v-model="scheduleInfo.ticketPrice" style="width: 100%"></el-input>
              </el-col>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addScheduleInfo">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
</template>

<script>
    import {getCurrentPageMovieSchedule,
    getAllMovie,
    getAllHall,
    getHasScheduleDateTime,
    addScheduleInfo
    ,deleteMovieSchedule} from '../../../api/index'
     import {MessageBox,Message} from 'element-ui'
    export default {
        name: "MovieSchedule",
        data() {
          let checkPrice = (rule, value, callback) => {
            if (!value) {
              callback(new Error('售价不能为空'));
            } else {
              if (/((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/.test(value)){
                callback();
              } else{
                callback(new Error('请输入正确格式的售价'));
              }
            }
          };
          return {
            //服务器地址
            server:'http://localhost:3000',
            scheduleTime: new Date(),
            tableData:[],
            total:0,
            movieDuration:0,
            pageSize:6,
            currentPage:1,
            scheduleInfo:{},
            curEndTime:"",
            dialogFormVisible:false,
            addDialogFormVisible:false,
            dialogTitle:'',
            labelPosition:'right',
            input:'',
            searchInput:'',
            rules: {
              movieValue: [
                { required: true, message: '电影名不能为空', trigger: 'change' },
              ],
              cinemaValue: [
                { required: true, message: '影院名不能为空', trigger: 'change' },
              ],
              hallValue: [
                { required: true, message: '影厅名不能为空', trigger: 'change' },
              ],
              movieShowDate: [
                { required: true, message: '放映日期不能为空', trigger: 'change' },
              ],
              // movieShowTime: [
              //   { required: true, message: '放映时间不能为空', trigger: 'change' },
              // ],
              price: [
                { required: true, message: '售价不能为空', trigger: 'blur' },
                { validator: checkPrice, trigger: 'blur' }
              ]
            },

            movieOptions: [],

            cinemaOptions: [],

            hallOptions: [],

            timeOptions:[],

            moviePublicDate:'',

            datePickerOptions:{
              disabledDate: this.disabledDate
            }
          }
        },
        created(){
          this.loadCurrentPageMovieSchedule(this.currentPage,this.pageSize,'');
        },
        methods: {
          async loadCurrentPageMovieSchedule(currentPage,pageSize,input){
            let json = await getCurrentPageMovieSchedule(currentPage,pageSize,this.$cookies.get("cinemaId"),input);
            if (json.code===0){
              this.tableData = json.data.records;
              this.total = json.data.total;
            }
          },
          async currentChange(currentPage){
            this.currentPage = currentPage;
            this.loadCurrentPageMovieSchedule(this.currentPage,this.pageSize,this.searchInput);
          },
          handleEdit(index, row) {
            console.log(index, row);
          },
          async handleDelete(index, row) {
            MessageBox.confirm('此操作将永久删除该排片所有信息, 是否继续？','提示').then(async (value)=>{
              if (value==='confirm'){
                let json = await deleteMovieSchedule(row.scheduleId);
               
                if (json.code===0){
                  Message.success('删除该电影排片成功！');
                  this.loadCurrentPageMovieSchedule(this.currentPage,this.pageSize,this.searchInput);
                 // console.log(this.tableData);
                }
              }
            });
          },
          //搜索电影
          search(){
            this.searchInput = this.input;
            this.loadCurrentPageMovieSchedule(1,this.pageSize,this.searchInput);
          },
          //新增电影排片
          async addSchedule(){
            this.scheduleInfo = {};
            //获取电影上映日期,保证在上映后才能排片
            this.moviePublicDate = '';

            let json = await getAllMovie();
            if (json.code===0){
              console.log(json);
              this.movieOptions = json.data;

            }
            //传电影院ID,登录后修改
            json = await getAllHall(this.$cookies.get("cinemaId"));
            if (json.code===0){
              this.hallOptions = json.data;
            }
            this.addDialogFormVisible = true;
          },
          //选择电影
          changeMovie(value){
            if (value){
              this.movieOptions.forEach((val)=>{
                if (val.id===value){
                  this.moviePublicDate = val.releaseTime;
                  this.movieDuration = val.duration;
                }
              })
            }
          },
          //选择电影放映日期  <-他这里是将时间选择值写固定
          async movieShowDateChange(value){
            //console.log(value);
            //console.log(this.scheduleInfo.movieShowDate);  

          },
          //限制可选日期
          disabledDate(time){
            if (this.scheduleInfo.movieValue){
              if (new Date(this.moviePublicDate)-new Date()>0){
                return time.getTime() < new Date(this.moviePublicDate);
              } else{
                return time.getTime() < new Date()
              }
            } else{
              return time.getTime() > 0;
            }
          },
          getEndTime(startTime,min){
            var date= new Date(this.scheduleInfo.movieShowDate+" "+ startTime);
            var curMin=date.getMinutes();  //2. 获取当前分钟
            min = parseInt(min);
            date.setMinutes(curMin+min);  //3. 设置当前时间+10分钟：把当前分钟数+10后的值重新设置为date对象的分钟数
            var h = date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours()
            var f = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()
            var formatdate =  h + ":" + f + ":" + "00";
            this.curEndTime = formatdate;
            this.scheduleInfo.endTime = formatdate;
            return formatdate;
          },
          async addScheduleInfo(){
            if (this.scheduleInfo.movieValue
            && this.scheduleInfo.hallValue
            && this.scheduleInfo.movieShowDate
            && this.scheduleInfo.startTime
            && this.scheduleInfo.endTime
            && this.scheduleInfo.ticketPrice&&/((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/.test(this.scheduleInfo.ticketPrice)) {
              //登录后修改
              let json = await addScheduleInfo(this.scheduleInfo.movieValue,
                                              this.scheduleInfo.hallValue,
                                              this.$cookies.get("cinemaId"),
                                              this.scheduleInfo.movieShowDate,
                                              this.scheduleInfo.startTime,
                                              this.scheduleInfo.endTime,
                                              this.scheduleInfo.ticketPrice);
              //console.log(json);
              if (json.code===0){
                Message.success('添加电影排片成功！');
                this.addDialogFormVisible = false;
                this.loadCurrentPageMovieSchedule(this.currentPage,this.pageSize,this.searchInput);
              }else{
                 Message.error(json.msg);
              }
            } else{
              Message.error('请完成必填内容！');
            }
          }
        },
    }
</script>

<style>
  .schedule-table{
    width:90%;
    min-width:900px;
    margin: 0 auto;
    margin-bottom: 30px;
  }
  .top{
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30px 0;
    margin-bottom: 30px;
  }
  .block{
    text-align: center;
  }
  .el-dialog__header{
    text-align: center;
  }
  .el-dialog__body .el-form-item{
    padding-left: 20%;
  }
</style>
